package com.logic.idevice.impl.dt51

import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.logic.idevice.IUHFScan
import com.sinopec.basemodule.constants.PreferencesConstant
import com.sinopec.basemodule.dialog.TankerProgressDialog
import com.sinopec.basemodule.utils.kotlin.NumberUtils
import com.sinopec.basemodule.utils.kotlin.parseInt
import com.sinopec.basemodule.utils.kotlin.validationRfidRule
import com.ubx.usdk.USDKManager
import com.ubx.usdk.rfid.RfidManager
import com.ubx.usdk.rfid.aidl.IRfidCallback
import com.ubx.usdk.util.SoundTool
import com.uhf.uhf.R
import java.math.RoundingMode
import java.util.*
import java.util.Collections.emptyList

/**
 * @author lwj
 * @ClassName: DT51Scan
 * @Description: DT51手持扫码模块
 */
class DT51Scan(
    override val callRefreshText: IUHFScan.IRefreshSpeed,
    override val callDataRefresh: IUHFScan.IRefreshData,
    override val callScanStatusChange: IUHFScan.IScanStatus
) : IUHFScan {
    val TAG = "DT51-" + DT51Scan::class.java.simpleName
    private var mRfidManager: RfidManager? = null
    private var RFID_INIT_STATUS = false
    private lateinit var loading: TankerProgressDialog
    var readerType = 0

    //开始扫码时间戳
    private var startTimeMillis = 0L
    //没有过滤的总编码数（计算速度用）
    private var tagTotal = 0
    //速度
    var speed = "0"

    //是否正在扫码
    var isScan = false
    private val codeList = ArrayList<String>()
    var content: AppCompatActivity? = null
    override fun init(activity: AppCompatActivity) {
        this.content = activity
        loading = TankerProgressDialog(activity, R.style.CustomDialog)
        loading.setCanceledOnTouchOutside(false)

        activity.lifecycle.addObserver(LifecycleEventObserver { source, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    initUhf(activity)
                }
                Lifecycle.Event.ON_START -> {

                }
                Lifecycle.Event.ON_RESUME -> {

                }
                Lifecycle.Event.ON_PAUSE -> {

                }
                Lifecycle.Event.ON_DESTROY -> {
                    RFID_INIT_STATUS = false
                    USDKManager.getInstance().release()
                    if (mRfidManager != null) {
                        mRfidManager!!.disConnect()
                        mRfidManager!!.release()
                        Log.d(TAG, "onDestroyView: rfid close")
                    }
                }
                else -> {}
            }
        })
    }

    override fun startOrStop(isStart: Boolean) {
        callScanStatusChange.onScanStatusChange(isStart)
        if (RFID_INIT_STATUS) {
            //是否正在扫码
            isScan = isStart
            if (isStart) {//开始扫码
                Log.d(TAG, "--- startInventory()   ----")
                setCallback()
                if (mRfidManager != null) {
                    val startInt = mRfidManager!!.startRead() //少量标签盘点建议使用：0；盘点标签超过 100-200建议使用：1.
                    if (startInt != -1) {
                        //开始扫码时间戳
                        startTimeMillis = System.currentTimeMillis()
                        tagTotal = 0
                        speed = "0"
                    }
                    Log.d(TAG, "--- startInt=$startInt")
                }
            } else {
                Log.d(TAG, "--- stopInventory()   ----")
                if (mRfidManager != null) {
                    val stopInt = mRfidManager!!.stopInventory()
                    Log.d(TAG, "--- stopInt=$stopInt")
                }
            }
        } else {
            Log.d(TAG, "scanStartBtn  RFID未初始化 ")
        }
    }

    override fun isScanning(): Boolean {
        return isScan
    }

    override fun isCloseRfid(): Boolean {
       return true
    }

    override fun clear() {
        tagTotal = 0
        codeList.clear()
        callDataRefresh.onRefreshData(codeList)
    }

    override fun newestData(): List<String> {
        return emptyList()
    }


    private fun setCallback() {
        if (mRfidManager != null) {
            mRfidManager!!.registerCallback(object : IRfidCallback {
                override fun onInventoryTag(EPC: String, TID: String, strRSSI: String) {
                    tagTotal++
                    Log.d(
                        TAG,
                        "onInventoryTag:............... epc:$EPC    tid:$TID   strRSSI:$strRSSI  tagTotal:$tagTotal"
                    )
                    //添加声音
                    if (PreferencesConstant.getInstance().beeper_model != 0) {
                        SoundTool.getInstance(content).playBeep(1)
                    }

                    var strData = ""
                    if (!TID.isNullOrEmpty() && TID.length >= 12) {
                        strData = TID.substring(0, 12)
                        if (strData.validationRfidRule()) {
                            val scanResultEmp = strData.replace(" ".toRegex(), "")//无空格的
                            val scanResult =
                                scanResultEmp.replace("(.{2})(?=.{2})".toRegex(), "$1 ")//两位一空格
                            if (!codeList.contains(scanResult)) {
                                codeList.add(scanResult)
                            }
                        }
                    }
                    val currentTimeMillis = System.currentTimeMillis()
                    //计算时间差
                    val time = (currentTimeMillis - startTimeMillis) / 1000 //将毫秒转换成秒
                    Log.d(TAG, "time=$time")

                    if(time > 0){
                        speed = NumberUtils.div(tagTotal.toString(), 0, RoundingMode.DOWN, time.toString())
                    }
                    //ui线程中更新界面
                    content!!.runOnUiThread {
                        callRefreshText.onRefreshSpeed(
                            codeList.size,
                            speed.parseInt(),
                            time
                        )
                        callDataRefresh.onRefreshData(codeList)
                    }

                }

                override fun onInventoryTagEnd() {
                    Log.d(TAG, "onInventoryTagEnd()")
                    callScanStatusChange.onScanStatusChange(false)
                }
            })
        }
    }

    private fun initUhf(context: AppCompatActivity) {
        USDKManager.getInstance().release()
        if (mRfidManager != null) {
            mRfidManager!!.disConnect()
            mRfidManager!!.release()
            Log.d(TAG, "initUhf: rfid close")
        }
        loading.setText("连接设备")
        loading.show()
        // 在异步回调中拿到RFID实例
        USDKManager.getInstance().init { status ->
            if (status) {
                loading.dismiss()
                Log.d(TAG, "initRfid()  success.")
                RFID_INIT_STATUS = true
                mRfidManager = USDKManager.getInstance().rfidManager
                //读码区域 queryMode 0:epc 1:epc+tid 2:epc+user
                if (mRfidManager != null) {
                    mRfidManager!!.queryMode = 2
                    val curQueryMode = mRfidManager!!.queryMode
                    mRfidManager!!.setOutputPower(DT51Setting.pow.toByte())
                    Log.d(TAG, "onItemSelecteda: $curQueryMode")
                }
            } else {
                Log.d(TAG, "initRfid  fail.")
                loading.dismiss()
            }
        }
    }
}